package org.monitor.servlet.base;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.monitor.config.MonitorConfig;
import org.monitor.kit.IDKit;
import org.monitor.servlet.pairs.Pairs;
import org.monitor.servlet.pairs.PairsBuilder;

public abstract class BaseUploadServlet extends BaseHttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected PairsBuilder getPairsBuilder(HttpServletRequest req) {
		PairsBuilder builder = super.getPairsBuilder(req);
		try {
			initFiles(req, builder);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return builder;
	}

	private Pairs initFiles(HttpServletRequest req, PairsBuilder builder) throws Exception {
		ServletFileUpload upload = getFileUpload();
		
		// 设置允许上传的最大文件大小 4M
		upload.setSizeMax(MonitorConfig.get().getMaxSize() * 1024);
		// 解析HTTP请求消息头
		List<FileItem> fileItems = upload.parseRequest(req);
		Iterator<FileItem> iter = fileItems.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = item.getString();
				builder.addPair(name, value);
				
			}else {
				// 此时的文件名包含了完整的路径，得注意加工一下
				String filename = item.getName();
				int index = filename.lastIndexOf("\\");
				if(index == -1){
					index = filename.lastIndexOf("/");
				}
				filename = filename.substring(index + 1, filename.length());
				
				long fileSize = item.getSize();
				
				if("".equals(filename) && fileSize == 0) {
					// 空文件
					continue;
				}
				String[] strs = filename.split("\\.");
				String tmpName = IDKit.gen() + "." + strs[strs.length - 1];
				String filePath = MonitorConfig.get().getTmpDir() + "/" + tmpName;
				File uploadFile = new File(filePath);
				item.write(uploadFile);
				builder.addFile(filename, filePath);
			}
			
		}
		
		return builder.build();
	}
	
	private ServletFileUpload getFileUpload() {
		DiskFileItemFactory diskFactory = new DiskFileItemFactory();
		// threshold 极限、临界值，即硬盘缓存 1M
		diskFactory.setSizeThreshold(1024 * 1024);
		// repository 贮藏室，即临时文件目录
		diskFactory.setRepository(new File(MonitorConfig.get().getTmpDir()));
		ServletFileUpload upload = new ServletFileUpload(diskFactory);
		return upload;
	}

}
